import { defineStore } from 'pinia'
import { ref } from 'vue'
import { LoginAPI } from '@/apis/user';
import { useCartStore } from './cartStore';
import { mergeCartAPI } from '@/apis/cart';

export const useUserStore = defineStore('user', () => {
    //定义用户数据
    const userInfo = ref({})
    const cartStore = useCartStore()

    //拿到用户数据
    const getUserInfo = async ({ account, password }) => {
        const res = await LoginAPI({ account, password });
        userInfo.value = res.result;

        //合并购物车数据
        await mergeCartAPI(cartStore.cartlist.map(item => {
            return {
                skuId: item.skuId,
                selected: item.selected,
                count: item.count
            }
        }))

        cartStore.updateCartList();
    }




    //清除用户数据
    const clearUserInfo = () => {
        userInfo.value = {}
        cartStore.clearCartList()
    }
    return {
        userInfo,
        getUserInfo,
        clearUserInfo
    }
}, {
    persist: true,
}
)